// 设置cookie
"use strict";
function getElement() {
  console.log("content.js loaded");
}

getElement();

function setCookie(c_name, value) {
  document.cookie = c_name + "=" + value;
}

// setCookie("test", "11111111113333");
// console.log(document.cookie);
// console.log(getCookie("test"));

function getCookie(name) {
  var arr,
    reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if ((arr = document.cookie.match(reg))) return unescape(arr[2]);
  else return null;
}

// 读取cookie
/**
 * 获取指定名称的Cookie值
 * @param {string} c_name - 要查找的Cookie名称
 * @returns {string} 返回找到的Cookie值，如果未找到则返回空字符串
 */
function getCookie(c_name) {
  if (document.cookie.length > 0) {
    let c_start = document.cookie.indexOf(c_name + "=");
    if (c_start != -1) {
      c_start = c_start + c_name.length + 1;
      let c_end = document.cookie.indexOf(";", c_start);
      if (c_end == -1) c_end = document.cookie.length;
      return unescape(document.cookie.substring(c_start, c_end));
    }
  }
  return "";
}

// 检查cookie
function checkCookie(c_name) {
  username = getCookie(c_name);
  console.log(username);
  if (username != null && username != "") {
    return true;
  } else {
    return false;
  }
}

// 清除cookie
function clearCookie(name) {
  setCookie(name, "", -1);
}

//content.js获取到cookie并调用api 将结果返回po.js
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  let csrf = getCookie("bili_jct");
  request.csrf = csrf;
  // request.append("csrf", csrf);
  switch (request.action) {
    case "GetProgress":
      (async () => {
        if (request.p_now == null || request.p_now <= 1) {
          sendResponse(0);
        } else {
          const done = await getDuration(
            request.bvid,
            1,
            request.p_now - 1,
            request.section_idx
          );
          const total = await getDuration(
            request.bvid,
            1,
            request.len,
            request.section_idx
          );
          // return [time_h, time_m, time_s]
          // 将时间转换为秒
          const done_s = done[0] * 3600 + done[1] * 60 + done[2];
          const total_s = total[0] * 3600 + total[1] * 60 + total[2];
          // 计算进度条的宽度
          const width = (done_s / total_s) * 100;
          console.log("水真汽助手 - progress now:", width);
          sendResponse(width.toFixed(2));
        }
      })();
      return true;
    case "GetVideoInfo":
      (async () => {
        const res = await getVideoInfo(request.bvid);
        console.log("水真汽助手 - video info received:", res);
        sendResponse(res);
      })();
      return true;
    case "GetDuration":
      //! async+闭包
      // ref: https://stackoverflow.com/questions/53024819/sendresponse-not-waiting-for-async-function-or-promises-resolve
      (async () => {
        const res = await getDuration(
          request.bvid,
          request.p1,
          request.p2,
          request.section_idx
        );
        console.log("水真汽助手 - data received:", res);
        sendResponse(res);
      })();
      return true; //! 保持消息通道打开，直到sendResponse被调用；否则，sendResponse可能会在异步代码执行之前被调用
    case "InsertMarker": // p_mark: 要插入标记的视频集号; bvid: 视频的bvid
      insertMarker(request.p_mark, request.bvid);
      sendResponse("InsertMarker done!");
      break;
    case "submitAppeal": // p_mark: 要插入标记的视频集号; bvid: 视频的bvid
      (async () => {
        const res = await submitAppeal(request);
        // console.log("水真汽助手 - submitAppeal received:", res);
        sendResponse(res);
      })();
      return true;
    default:
      console.log("水真汽助手 - content.js received message");
  }
});
